package org.jeecg.modules.zhima.base.shiro.realms;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.jeecg.modules.zhima.base.shiro.service.TokenService;
import org.jeecg.modules.zhima.base.shiro.token.JwtToken;
import org.jeecg.modules.zhima.center.entity.UmsMember;
import org.jeecg.modules.zhima.portal.service.IUserService;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @author lixiao
 * @date 2019/8/6 10:02
 */
@Slf4j
public class JwtRealm extends AuthorizingRealm {

    @Resource
    private TokenService tokenService;

    @Resource
    private IUserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        UmsMember loginUser = tokenService.getLoginUser();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        // 添加角色
//        authorizationInfo.addRoles(loginUser.getRoleSet());
//        // 添加权限
//        authorizationInfo.addStringPermissions(loginUser.getPermissionsSet());
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        String type = tokenService.getType(token);
        log.info("token auth start - {}...", type);
        UmsMember user;
        String secret;
        if (type.equals(TokenService.TYPE_WEIXIN)){
            String wxOpenId = tokenService.getWxOpenId(token);
            user = userService.getMemberByWxOpenId(wxOpenId);
            if (user == null) {
                throw new IncorrectCredentialsException();
            }
            secret = wxOpenId;
        }else {
            // 获得phone
            String phone = tokenService.getPhone(token);
            if (StringUtils.isEmpty(phone)) {
                throw new IncorrectCredentialsException();
            }
            user = userService.getMemberByPhone(phone);
            if (user == null) {
                throw new IncorrectCredentialsException();
            }
            secret = user.getPassword();
        }

        try {
            boolean verify = tokenService.verify(token, secret);
            if (verify == Boolean.FALSE) {
                throw new IncorrectCredentialsException();
            }
        } catch (Exception e) {
            throw new IncorrectCredentialsException();
        }
        return new SimpleAuthenticationInfo(token, token, "JwtRealm");
    }
}
